/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */


const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/Services.jsm");

Cu.import("resource://savefileto/common.jsm");

const DEFAULT_DIRECTORY = "$Desk";


var dialog =
{
    get args()        { return window.arguments[0].args; },
    set result(value) { window.arguments[0].result = value; },
    
    get label() { return document.getElementById("tbox_label"); },
    get path()  { return document.getElementById("tbox_path"); },
    get menu()  { return document.getElementById("cbox_menu"); },
    
    get file()
    {
        return getFile(this.path.value.trim());
    },
    
    onLoad: function()
    {
        this._ = new StringBundle("chrome://savefileto/locale/folder.properties").getter;
        
        document.title = this._("title." + this.args.title);
        
        this.label.value = this.args.label;
        this.path.value = this.args.path;
        this.menu.checked = this.args.menu;
    },
    
    pickFolder: function()
    {
        let self = this;
        this.openFolderPicker(this.file, function(result, filePicker)
        {
            if (result == Ci.nsIFilePicker.returnOK)
            {
                let name = filePicker.file.leafName;
                let path = self._getFolderPath(filePicker.file, self.path.value.trim());
                self._updateFolder(name, path);
            }
        });
    },
    
    pickVariable: function()
    {
        let winArgs = {result: null /* {file, path} */};
        winArgs.wrappedJSObject = winArgs;
        
        Services.ww.openWindow(
            window,
            "chrome://savefileto/content/prefwindow/variable.xul",
            null,
            "chrome,centerscreen,all,modal",
            winArgs);
        
        if (! winArgs.result)
            return;
        
        this._updateFolder(winArgs.result.file.leafName, winArgs.result.path);
    },
    
    openFolderPicker: function(file, callback)
    {
        var filePicker = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
        
        if (! (file && file.exists() && file.isDirectory()))
            file = getFile(DEFAULT_DIRECTORY);
        filePicker.displayDirectory = file;
        
        var title = this._("folderPickerTitle");
        var mode = Ci.nsIFilePicker.modeGetFolder;
        filePicker.init(window, title, mode);
        filePicker.open(function(result) { callback(result, filePicker); });
    },
    
    _updateFolder: function(name, path)
    {
        if (this.label.value.trim().length == 0)
            this.label.value = name;
        
        this.path.value = path;
    },
    
    _getFolderPath: function(newFile, oldPath)
    {
        if (oldPath.charAt(0) == "$")
        {
            try
            {
                let index = oldPath.search(/[/\\]/);
                let name = oldPath.substring(1, ((index != -1) ? index : oldPath.length));
                let nameFile = Services.dirsvc.get(name, Ci.nsIFile);
                
                if (newFile.path.startsWith(nameFile.path))
                    return newFile.path.replace(nameFile.path, "$" + name);
            }
            catch (e)
            {
                Cu.reportError(e);
            }
        }
        
        return newFile.path;
    },
    
    onDialogAccept: function()
    {
        try
        {
            var label = this.label.value.trim();
            if (! label)
                throw this._("error.emptyName2");
            
            var path = this.path.value.trim();
            if (! path)
                throw this._("error.emptyPath2");
            
            var file = this.file;
            if (! (file && file.exists() && file.isDirectory()))
                throw this._("error.folderNotFound2", (file ? file.path : path));
            
            var menu = this.menu.checked;
            
            this.result = {label: label, path: path, menu: menu};
            return true;
        }
        catch (e if (typeof(e) == "string"))
        {
            var title = this._("error.title");
            var message = e;
            Services.prompt.alert(window, title, message);
            return false;
        }
    }
}
